// let Promise1 = require('./myPromise');
let fs = require('fs');
function read(filename){
    return new Promise((resolve,reject) => {
        fs.readFile(filename,'utf8',(err,data)=>{
            if(err) return reject(err)
            return resolve(data)
        })
    })
}
// let p1 = read('./promise/name.txt').then((data)=>{
//     return read('./promise/'+data)
// },(err)=>{
//     console.log(err)
// })
// p1.then((data)=>{
//     console.log(data);
// },err=>{
//     console.log(err);
// })

// let p2 = new Promise1((resolve,reject)=>{
//     reject(100)
// })
// p2.then().then().then((data)=>{
//     console.log(data);
// },err=>{
//     console.log(err);
// })

//Promise.all
Promise.all = function(values){
  return new Promise((resolve,reject)=>{
    let arr = [];
    let count = 0;//并发用计数器
    function processData(key,value){
      arr[key] = value; //将结果和数据对应起来
      if(++count === values.length){
        resolve(arr); //成功后把结果抛出来
      }
    }
    for(let i=0;i<values.length;i++){
      let current = values[i];
      let then = current.then;
      if(then && typeof then === 'function'){ //是一个promise
        then.call(current,y=>{ //是promisede就让promise执行
          processData(i,y);
        },reject);//如果其中一个promise出错，就停止执行
      }else{
        processData(i,current); //常量直接发返回
      }
    }
  })
}

Promise.all([read('./promise/age.txt'),read('./promise/name.txt'),1,2,3]).then(data=>{
  console.log(data)
})

//Promise.race赛跑，有一个成功就返回成功，有一个失败就返回失败，返回最快的那个
Promise.race = function(values){
 return new Promise((resolve,reject)=>{
  for(let i=0;i<values.length;i++){
    let current = values[i];
    let then = current.then;
    if(then && typeof then === 'function'){ //是一个promise
      then.call(current,y=>{ //是promisede就让promise执行
        resolve(y)
      },reject);//如果其中一个promise出错，就停止执行
    }else{
      resolve(current);
    }
  }
 })
}
Promise.race([read('./promise/age.txt'),read('./promise/name.txt'),11,22,33]).then(data=>{
  console.log(data)
})

//promisify  bluebird
let fs1 = require('fs');
function promisify(fn){ //把方法promise化
  return function(){
    return new Promise((resolve,reject)=>{
      fn(...arguments,function(err,data){
        if(err) reject(err);
        resolve(data);
      })
    })
  }
}

let read1 = promisify(fs1.readFile);
read1('./promise/name.txt','utf8').then(data=>{
  console.log(data);
})

let write = promisify(fs1.writeFile);
//写入的必须是字符串
write('./promise/name.txt','123').then(data=>{
  console.log('写入成功');
})

//mz库，基于promise封装的
//npm install mz
let mz = require('mz/fs');
mz.readFile('./promise/name.txt','utf8').then(data=>{
  console.log(data);
})